<?php

/**
 * myvideo actions.
 *
 * @package    sf_sandbox
 * @subpackage myvideo
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class myvideoActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
	
	 public function executeDel(sfWebRequest $request)
  {
  	   $m = VideoPeer::retrieveByPK($request->getParameter('id'));
  	   $this->forward404Unless($m);
  	   if($m->getUserId()==$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ) or $this->getUser()->isSuperAdmin())
  	   {
  	   	 $m->delete();
  	     $this->getUser ()->setFlash ( 'message', 'Video was deleted' );
  	   }
  	   $this->redirect('myvideo/index');
  }
	
  public function executeIndex(sfWebRequest $request)
  {
  		$this->form = new VideoForm ( );
		$c = new Criteria();
		$c->add(VideoPeer::USER_ID,$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
		
		$pager = new sfPropelPager('Video', sfConfig::get('app_video_perpage'));
        $pager->setCriteria($c);
        $pager->setPeerMethod('doSelect');        
        $pager->setPage($this->page);
        $pager->init();
        $this->video = $pager;
        
        		if ($request->isMethod ( 'post' )) 

		{ 
			$this->form = new VideoForm ( );
			$this->form->bind ( $request->getParameter ( 'video' ), $request->getFiles ( 'video' ) );
			if ($this->form->isValid ()) {
				
				$this->form->save ();
				$this->redirect('@my_video');
			}
		
		}
  		
		///Кидаем пользователя в layout
	     $this->getRequest()->setAttribute('v', $this->getUser()->getProfile());
		////
  	
  }
  
  public function executeEdit(sfWebRequest $request)
  {
        $this->form = new VideoForm ();
        if ($request->isMethod ( 'post' )) 

		{ 
			
			$this->form->bind ( $request->getParameter ( 'video' ), $request->getFiles ( 'video' ) );
			if ($this->form->isValid ()) {
				
				  $this->form->save ();
				  
				  if($this->getUser()->getProfile()->getGender()=='m')
					  {
					  	 $now = new sfDate();	  	 
					  	 $g = $this->form->getObject();
					  	 $g->setUserId($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
					  	 $g->setDateExpire($now->addDay(30)->dump());
					  	 if(sfConfig::get('app_video_autoapprove')=='true')
					  	 {
					  	 	$g->setPub(3);
					  	 }
					  	 else 
					  	 {
					  	 	$g->setPub(1);
					  	 }
					  	 $g->save();
					  	
				
					  	 	    $u = $this->getUser()->getProfile();
						  	    if($u->getAccount()<sfConfig::get('app_cost_video_add') and sfConfig::get('app_use_payment_add_video')=='true')
								{
									$this->getUser ()->setFlash ( 'error', 'У вас недостаточно средств на счете' );
									$this->redirect('@account');
								}
								else 
								{
									if(sfConfig::get('app_use_payment_add_video')=='true')
									{
											 $u->setAccount($u->getAccount()-sfConfig::get('app_cost_video_add'));
							                 $u->save();
							
											 $pa = new Payment();
											 $pa->setUserId($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
											 $pa->setPaymentId($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
											 $pa->setLevelId(10);
											 $pa->setSumma(sfConfig::get('app_cost_video_add'));
											 $pa->setDirection(0);
											 $pa->save();
							 
								             $this->getUser ()->setFlash ( 'message', __('За создание видеоролика с вашего счета снято %1% кредитов',array('%1%'=>sfConfig::get('app_cost_video_add'))) );
									}
								}
								  	
					  }	
					  if($this->getUser()->getProfile()->getGender()=='w')
					  {
					  	 	  	 
					  	 $g = $this->form->getObject();
					  	 $g->setUserId($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
						   if(sfConfig::get('app_video_autoapprove')=='true')
						  	 {
						  	 	$g->setPub(3);
						  	 }
						  	 else 
						  	 {
						  	 	$g->setPub(1);
						  	 }
					  	 $c = new Criteria();
			  	        $g->save();
					  }
				
				
				
				
				
				//die;
				$this->redirect('@video_show?id='.$this->form->getObject()->getId());
			}
		
		}
  	
  			///Кидаем пользователя в layout
	     $this->getRequest()->setAttribute('v', $this->getUser()->getProfile());
		////
  }
  
  
  
  

	public function executeTryshow(sfWebRequest $request)
  {
  	
  	 $this->m = VideoPeer::retrieveByPK($request->getParameter('id'));
  	 $this->forward404Unless($this->m);
  	 $this->user = $this->m->getsfGuardUser();
  	 ///Снимаем бабло
  	 if($this->m->getUserId()!=$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ) and $this->m->getsfGuardUser()->getGender()=='w' and $this->getUser()->getProfile()->getIsVip()==false)
  	 {
  	 	

  	  	$u = $this->getUser()->getProfile();
  	 	 if($u->getAccount()<sfConfig::get('app_cost_video_show'))
				{
					$this->getUser ()->setFlash ( 'error', 'У вас недостаточно средств на счете' );
					$this->redirect('@account');
				}
				else 
				{
				             $this->getUser ()->setFlash ( 'message', __('За просмотр видеоролика с вашего счета снято %1% кредитов', array('%1%'=>sfConfig::get('app_cost_video_show'))) );
				}
  	 }
  	 $this->redirect('myvideo/show?id='.$request->getParameter('id'));
  	 ////
  	
  }
	
	
	
	public function executeShow(sfWebRequest $request)
  {
      	////Проверка на регистрацию
  	if(!$this->getUser()->isAuthenticated())
  	{
  	 $this->getUser ()->setFlash ( 'error', 'Только для зарегистрированных пользователей' );
  	 $this->redirect('@registration');
  	}
  	
  	 $this->m = VideoPeer::retrieveByPK($request->getParameter('id'));
  	 $this->forward404Unless($this->m);
  	 $this->user = $this->m->getsfGuardUser();
  	 
  	 
  	 ///Снимаем бабло
  	 if($this->m->getUserId()!=$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ) and $this->m->getsfGuardUser()->getGender()=='w')
  	 {
  	 	
           
  	  	$u = $this->getUser()->getProfile();
  	 	 if($u->getAccount()<sfConfig::get('app_cost_video_show'))
				{
					$this->redirect('@account');
				}
				else 
				{
  	 				 		 $u->setAccount($u->getAccount()-sfConfig::get('app_cost_video_show'));
			                 $u->save();
			
							 $pa = new Payment();
							 $pa->setUserId($this->user->getId());
							 $pa->setPaymentId($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
							 $pa->setLevelId(6);
							 $pa->setSumma(sfConfig::get('app_cost_video_show'));
							 $pa->setDirection(0);
							 $pa->save();
			 
				            $this->getUser ()->setFlash ( 'message', __('За просмотр видеоролика с вашего счета снято %1% кредитов', array('%1%'=>sfConfig::get('app_cost_video_show'))) );
				}
  	 }
  	 ////
  	 
     
    		 /*  Передаем пользователя в layout
		     * 
		     */
		$this->getRequest ()->setAttribute ( 'v', $this->user );
  	 
  }
  
  	public function executeList(sfWebRequest $request)
  {
  	 $this->user = sfGuardUserPeer::retrieveByPK($request->getParameter('id'));
  	 
  	 $this->forward404Unless($this->user);
  	    $c = new Criteria();
		$c->add(VideoPeer::USER_ID,$this->user->getId());
		
		////Проверка на дату окончания и опубликование если смотрит не хозяин
		if($this->user->getId()!=$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ) and sfConfig::get('app_video_autoapprove')!='true')
		{
			
			$c->add(VideoPeer::DATE_EXPIRE,date("Y-m-d"),Criteria::GREATER_EQUAL);
			$c->addAnd(VideoPeer::PUB,3);
		}
		//
		
		$pager = new sfPropelPager('Video', sfConfig::get('app_video_perpage'));
        $pager->setCriteria($c);
        $pager->setPeerMethod('doSelect');        
        $pager->setPage($this->page);
        $pager->init();
        $this->video = $pager;
        
      
    		 /*  Передаем пользователя в layout
		     * 
		     */
		$this->getRequest ()->setAttribute ( 'v', $this->user );
		
  }
  
    	public function executeDownload(sfWebRequest $request)
  {
  	    $file = VideoPeer::retrieveByPK($request->getParameter('id'));
  	    $this->forward404Unless($file);
  	    $path = sfConfig::get('sf_upload_dir').'/users/video/'.$file->getVideoPath();
  	    
  	    $u = $this->getUser()->getProfile();
  	    $this->forward404Unless($u);
  	    if($u->getAccount()>sfConfig::get('app_cost_video_download'))
			{
				   $u->setAccount($u->getAccount()-sfConfig::get('app_cost_video_download'));
				   $u->save();
	
				   $pa = new Payment();
				   $pa->setUserId($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
				   $pa->setPaymentId($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
				   $pa->setLevelId(7);
				   $pa->setSumma(sfConfig::get('app_cost_video_download'));
				   $pa->setDirection(0);
				   $pa->save();				
			}
			else 
			{
				$this->getUser ()->setFlash ( 'error', 'У вас недостаточно средств на счете' );
				$this->redirect('@account');
				
			}
  	    
  	    
  	    $cn = file_get_contents($path);
  	    header("Content-type: video/avi");
  	    header("Content-Disposition: attachment; filename=video.avi");
  	    Header("Cache-Control: no-cache, must-revalidate"); 
        header("Content-Type: application/octet-stream"); 	    
  	    echo $cn;
  }

  
  public function executeDone(sfWebRequest $request)
  {
       
  }  	
  
  
}
